<?php

/**
 * ECTouch Open Source Project
 * ============================================================================
 * Copyright (c) 2012-2014 http://ectouch.cn All rights reserved.
 * ----------------------------------------------------------------------------
 * 文件名称：ProjectControoller.class.php
 * ----------------------------------------------------------------------------
 * 功能描述：活动控制器
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.ectouch.cn/docs/license.txt )
 * ----------------------------------------------------------------------------
 */
/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class ProjectController extends CommonController {

    private $size = 10;
    private $page = 1;
    private $cat_id = 0;
    private $keywords = '';

    public function __construct() {
        parent::__construct();
        $this->cat_id = intval(I('get.id'));
    }

	public function index(){
	$sql = 'SELECT cat_id, cat_name,file_url' .
            ' FROM {pre}project_cat ' .
            ' WHERE cat_type = 1 AND parent_id = 0 ' .
            ' ORDER BY sort_order ASC';
        $data = $this->model->query($sql);
        foreach($data as $key=>$vo){
            $data[$key]['url'] = url('project_list', array('id'=>$vo['cat_id']));
            $data[$key]['pic'] = $vo['file_url'];
            $data[$key]['name'] = $vo['cat_name'];
        }
	$this->assign('navigator', $data); //项目分类
    $this->assign('page_title','简创研习社'); //项目分类
	$this->display('project.dwt');
	}

    public function show(){	
	$this->display('project_show.dwt');
	}

	/**
     * ajax获取商品
     */
    public function ajax_index() {
        if (IS_AJAX) {
            $start = $_POST['last'];
            $limit = $_POST['amount'];
            $projects_list = model('Index')->projects_list($limit, $start);
            $list = array();
            // 热卖商品
            if ($projects_list) {
                foreach ($projects_list as $key => $value) {
                    $value['iteration'] = $key + 1;
                    $this->assign('projects', $value);
                    $list [] = array(
                        'single_item' => ECTouch::view()->fetch('library/asynclist_index_project.lbi')
                    );
                }
            }
            echo json_encode($list);
            exit();
        } else {
            $this->redirect(url('index'));
        }
    }

    /* ------------------------------------------------------ */

    //-- 活动分类
    /* ------------------------------------------------------ */
    public function project_cat() {
        $cat_id = I('get.id', 0, 'intval');
        $sql = 'SELECT cat_id, cat_name' .
            ' FROM {pre}project_cat ' .
            ' WHERE cat_type = 1 AND parent_id = '. $cat_id .
            ' ORDER BY sort_order ASC';
        $data = $this->model->query($sql);
        foreach($data as $key=>$vo){
            $data[$key]['url'] = url('project_list', array('id'=>$vo['cat_id']));
        }
        $this->assign('project_categories', $data); //活动分类树
        $this->display('project_cat.dwt');
    }

    /* ------------------------------------------------------ */

    //-- 活动列表
    /* ------------------------------------------------------ */
    public function project_list() {		
        $this->parameter();		
        $this->assign('keywords', $this->keywords);
        $this->assign('id', $this->cat_id);
		$projects_list = model('ProjectBase')->get_cat_projects($this->cat_id, $this->page, $this->size, $this->keywords);
		$count = model('ProjectBase')->get_project_count($this->cat_id, $this->keywords);
        $this->pageLimit(url('project_list', array('id' => $this->cat_id)), $this->size);
        $this->assign('pager', $this->pageShow($count));
        $this->assign('projects_list', $projects_list);
        //处理关键词描述
        $sql = "select * from ".M()->pre."project_cat where cat_id = ".$this->cat_id;
        $cat = M()->query($sql);
        if (!empty($cat['0']['keywords'])) {
            $this->assign('meta_keywords',htmlspecialchars($cat['0']['keywords']));
        }
        if (!empty($cat['0']['cat_desc'])) {
            $this->assign('meta_description',htmlspecialchars($cat['0']['cat_desc']));
        }
        $this->display('project_list.dwt');
    }

    /**
     * 活动列表异步加载
     */
    public function asynclist() {
        $this->parameter();
        $asyn_last = intval(I('post.last')) + 1;
        $this->size = I('post.amount');
        $this->page = ($asyn_last > 0) ? ceil($asyn_last / $this->size) : 1;
        $list = model('ProjectBase')->get_cat_projects($this->cat_id, $this->page, $this->size, $this->keywords);
        $id = ($this->page - 1) * $this->size + 1;
        foreach ($list as $key => $value) {
            $this->assign('id', $id);
            $this->assign('project', $value);
            $sayList [] = array(
                'single_item' => ECTouch::view()->fetch('library/asynclist_info.lbi')
            );
            $id++;
        }
        die(json_encode($sayList));
        exit();
    }

    /* ------------------------------------------------------ */
    //-- 活动详情
    /* ------------------------------------------------------ */
    public function info() {
		/* 微信分享设置 */
		$res = array();		
		$wxinfo   = model('Base')->model->table('wechat')->field('token, appid, appsecret')->find();
        $appid    = $wxinfo['appid'];
        $secret   = $wxinfo['appsecret'];
        
		//微信JS SDK
        $jssdk = new Jssdk($appid, $secret);
        $signPackage = $jssdk->GetSignPackage();

        $res['appid'] = $signPackage["appId"];
        $res['timestamp'] = $signPackage["timestamp"];
        $res['noncestr'] = $signPackage["nonceStr"];
        $res['signature'] = $signPackage["signature"];
		//
        $this->assign('res', $res);

        /* 项目详情 */
        $project_id = intval(I('get.aid'));
        $project = model('Project')->get_project_info($project_id);

		if($project['is_open']==0){
			if($project['user_id']==$_SESSION['user_id']){
             show_message('项目尚未通过审核', '点此修改', 'index.php?c=project&a=edit&project_id='.$project_id, 'info');
			}else{
			 show_message('项目尚未通过审核', '返回首页', 'index.php?c=project&a=index', 'info');
			}
		}

		//行业信息
		$project['cat_name']=model('Base')->model->table('project_cat')->field('cat_name')->where(array('cat_id'=>$project['cat_id']))->getOne();
		//分享摘要
		$project['description']="关注销售与市场,发现创业好项目。";

		$user_id=$project['user_id'];
		//微信头像
		$wechat_pic= model('Base')->model->table('wechat_user')->field('headimgurl')->where(array('ect_uid'=>$user_id))->getOne();
        //后台添加的头像
		$user_pic= model('Base')->model->table('users')->field('user_pic')->where(array('user_id'=>$user_id))->getOne();
				
        $this->assign('project', $project);
		$this->assign('wechat_pic', $wechat_pic);
        $this->assign('user_pic', $user_pic);

        /* 页面标题 */
        $page_info = get_page_title($project['cat_id'], $project['title']);
        $this->assign('page_title', htmlspecialchars($page_info['title']));
        /* meta */
        $this->assign('meta_keywords', htmlspecialchars($project['keywords']));
        $this->assign('meta_description', htmlspecialchars($project['description']));

		// 更新点击次数
        $data = 'click_count = click_count + 1';
        $this->model->table('project')->data($data)->where('project_id = ' . $project_id)->update();

		//获得活动的评论
		$comments = model('Comment')->get_comment_info($project_id, 3);
		$this->assign('comments', $comments);
		$comment_list = model('Comment')->get_comment($project_id, 1,3);
        $this->assign('comment_list', $comment_list);

		//是否已经收藏
        $is_collect= model('Base')->model->table('collect')->field('rec_id')->where(array('user_id'=>$_SESSION['user_id'],'item_id'=>$project_id,'item_type'=>3))->getOne();
        $this->assign('is_collect', $is_collect);
        $this->display('project_info.dwt');
    }

	/**
	* 添加收藏
	*/
	public function collect_add(){
            $project_id = intval(I('get.project_id'));
            $data_i['item_type'] = 3;
            $data_i['item_id'] = $project_id;
            $data_i['user_id'] = $_SESSION['user_id'];
            $data_i['add_time'] = gmtime();
            $this->model->table('collect')
                 ->data($data_i)
                 ->insert();
            show_message('收藏成功', '返回项目页面', 'index.php?c=project&a=info&aid='.$project_id, 'info');
	}

    /**
	* 取消收藏
	*/
	public function collect_del(){
            $project_id = intval(I('get.project_id'));            
			$where['user_id'] = $_SESSION['user_id'];
            $where['item_type'] = 3;
            $where['item_id'] = $project_id;
            $this->model->table('collect')
                 ->where($where)
                 ->delete();
            show_message('取消成功', '返回项目页面', 'index.php?c=project&a=info&aid='.$project_id, 'info');
	}

	/**
	* 发表评论
	*/
	public function comment_add(){
		if (IS_POST) {
			$project_id=I('post.project_id');
            $data_i['comment_type'] = 3;
            $data_i['comment_rank'] = 1;
            $data_i['id_value'] = $project_id;
            $data_i['user_id'] = $_SESSION['user_id'];
            $user_name=model('Base')->model->table('users')->field('user_name')->where(array('user_id'=>$_SESSION['user_id']))->getOne();
            $data_i['user_name'] = $user_name;
            $data_i['add_time'] = gmtime();
			$content=I('post.content');
			$content = strlen($content) > 100 ? mb_substr(htmlspecialchars($content), 0, 99) : htmlspecialchars($content);
            $data_i['content'] = $content;
            $this->model->table('comment')
                 ->data($data_i)
                 ->insert();
            show_message('发表成功,通过审核后才能显示。', '返回项目页面', 'index.php?c=project&a=info&aid='.$project_id, 'info');
		}
	}

	/**
     * 项目评论
     */
    public function comment_list()
    {
        $cmt = new stdClass();
        $cmt->id = !empty($_GET['id']) ? intval($_GET['id']) : 0;
        $cmt->type = !empty($_GET['type']) ? intval($_GET['type']) : 0;
        $cmt->page = isset($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
        $com = model('Comment')->get_comment_info($cmt->id,0);
        $this->assign('comments_info', $com);
        $comment_type = 3;
        $size = I(C('page_size'), 10);
        $this->assign('show_asynclist', C('show_asynclist'));
        $count = $com['count'];
        $filter['page'] = '{page}';
        $offset = $this->pageLimit(url('project/comment_list', $filter), $size);
        $offset_page = explode(',', $offset);
        $comment_list = model('Comment')->get_comment($cmt->id, $cmt->type, $comment_type, $offset_page[1], $offset_page[0]);
        $this->assign('comment_list', $comment_list);
        $this->assign('username', $_SESSION['user_name']);
        $this->assign('email', $_SESSION['email']);
        /* 验证码相关设置 */
        if ((intval(C('captcha')) & CAPTCHA_COMMENT) && gd_version() > 0) {
            $this->assign('enabled_captcha', 1);
            $this->assign('rand', mt_rand());
        }
        $result['message'] = C('comment_check') ? L('cmt_submit_wait') : L('cmt_submit_done');
        $this->assign('id', $cmt->id);
        $this->assign('type', $cmt->type);
        $this->assign('pager', $this->pageShow($count));
        $this->assign('title', '项目评论');
        $this->display('project_comment_list.dwt');
    }
    
    /**
     * 处理参数便于搜索商品信息
     */
    private function parameter() {
        $this->assign('show_asynclist', C('show_asynclist'));
        // 如果分类ID为0，则返回总分类页
        $page_size = C('article_number');
        $this->size = intval($page_size) > 0 ? intval($page_size) : $this->size;
        $this->page = I('request.page') ? intval(I('request.page')) : 1;
        $this->cat_id = intval(I('request.id'));
        $this->keywords = I('request.keywords');
    }

	/**
	*项目入驻
	*/
	public function verify(){	   
	   $this->display('project_verify.dwt');
	}

	/**
	*项目添加
	*/
	public function add(){
		/*初始化*/
       $project = array();
	   $this->assign('cat_select',  model('ProjectBase')->project_cat_list(0,$data[0]['cat_id']));
       $this->assign('act', 'insert');
	   $this->display('project_edit.dwt');
	}

	/**
	*项目添加
	*/
	public function insert(){	 
		//项目信息
		$data['title'] = I('post.title');
        $data['start_money'] = I('post.start_money');
		$data['cat_id'] = I('post.cat_id');
        $data['com_name'] = I('post.com_name');
        $data['com_address'] = I('post.com_address');
        $data['com_range'] = I('post.com_range');
        $data['com_birthday'] = I('post.com_birthday');
        $data['com_phone'] = I('post.com_phone');
        $data['add_time'] = gmtime();
		$data['user_id'] = $_SESSION['user_id'];
		$data['is_open'] = 0;
        $data['project_type'] = 0;

        //营业执照
        $file_url="";
		if ((isset($_FILES['file']['error']) && $_FILES['file']['error'] == 0) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none'))
		{			
			// 复制文件
			$res = $this->upload_com_file($_FILES['file']);
			if ($res != false)
			{
                $file_url=$res;
                $data['com_pic'] = $file_url;
                $project_id=$this->model->table('project')
                    ->data($data)
                    ->insert();
				show_message('提交成功', '请等待审核。', 'index.php?c=user&a=project_list&is_act=0', 'info');
			}
		}else{
				show_message('错误提示', '请上传营业执照', 'index.php?c=project&a=add', 'info');	
		}        
	}

	/**
	* 修改项目信息
	*/
	public function edit(){
		$project_id = intval(I('get.project_id'));
		$sql = 'SELECT * FROM {pre}project' .
            ' WHERE project_id=' .$project_id;
        $data = $this->model->query($sql);		
        $this->assign('project', $data[0]);
		$this->assign('cat_select',  model('ProjectBase')->project_cat_list(0,$data[0]['cat_id']));
		$this->assign('act', 'update');
        $this->display('project_edit.dwt');
	}

	/**
	* 修改项目信息
	*/
	public function update(){
		//营业执照
        $file_url="";
		if ((isset($_FILES['file']['error']) && $_FILES['file']['error'] == 0) || (!isset($_FILES['file']['error']) && isset($_FILES['file']['tmp_name']) && $_FILES['file']['tmp_name'] != 'none'))
		{			
			// 复制文件
			$res = $this->upload_com_file($_FILES['file']);
			if ($res != false)
			{
                $file_url=$res;
			}
		}

		if ($file_url == '')
		{
			$file_url = $_POST['com_pic'];
		}
		    $data['com_pic'] = $file_url;  
			$where['project_id'] = I('post.project_id');
            $data['title'] = I('post.title');
            $data['start_money'] = I('post.start_money');
			$data['cat_id'] = I('post.cat_id');
            $data['com_name'] = I('post.com_name');
            $data['com_address'] = I('post.com_address');
            $data['com_range'] = I('post.com_range');
            $data['com_birthday'] = I('post.com_birthday');
            $data['add_time'] = gmtime();
			$data['com_phone'] = I('post.com_phone');
            $this->model->table('project')
                        ->data($data)
                        ->where($where)
                        ->update();
	        show_message('修改成功', '返回', 'index.php?c=user&a=project_list&is_act=0', 'info');
	}	

	/* 上传文件 */
	function upload_com_file($upload)
	{
		$allow_mimes = array(
            'image/png' => '.png',
            'image/x-png' => '.png',
            'image/gif' => '.gif',
            'image/jpeg' => '.jpg',
            'image/pjpeg' => '.jpg'
        );
                
        if(!array_key_exists($upload['type'], $allow_mimes )) {
				show_message("只允许上传图片文件","返回","index.php?m=default&c=project&a=add","info");
        }

		//图片名随机
		$str = '';
        for ($i = 0; $i < 9; $i++) {
            $str .= mt_rand(0, 9);
        }

		$filename = gmtime() . $str.$allow_mimes[$upload['type']];
		$path     = ROOT_PATH."data/attached/com_pic/".$filename;
        $tmp_filename = $upload['tmp_name'];		
		if (move_uploaded_file($tmp_filename, $path))
		{
			return "data/attached/com_pic/" . $filename;
		}
		else
		{
			return false;
		}
	}

}